package openbang.chatroom.service.util;

import java.util.HashSet;

import javax.cache.CacheListener;

import openbang.chatroom.service.vo.CacheKeyDefine;


/**
 * 方法加上线程并发控制，避免遗漏数据
 * @author aibo zeng
 *
 */

public class OpenCacheListener implements CacheListener{
   	public OpenCacheListener(){    		
	}
	
	@Override
	public void onClear() {
	}

	@Override
	public void onEvict(Object key) {
	}

	@Override
	public void onLoad(Object key) {
	}

	@Override
	public synchronized void onPut(Object key) {
		if( key instanceof String){
			String keyStr = (String)key;
			if(keyStr.indexOf(CacheKeyDefine.SESSION_PREFIX)>=0){
				HashSet sAll = CacheHelper.getSessionAll();
				if(sAll.add(keyStr)){
				   //经测试,必须要重新放回,否则缓存里没有更新
				   CacheHelper.put(CacheKeyDefine.SESSION_ALL,sAll);
				}
			}
			else if(keyStr.indexOf(CacheKeyDefine.CHATGROUP_PREFIX)>=0){
				HashSet cAll = CacheHelper.getChatGroupAll();
				if(cAll.add(keyStr)){
				   CacheHelper.put(CacheKeyDefine.CHATGROUP_ALL,cAll);
				}
			}
			else{								
			}
		}
	}

	@Override
	public synchronized void onRmove(Object key) {
		if( key instanceof String){
			String keyStr = (String)key;
			if(keyStr.indexOf(CacheKeyDefine.SESSION_PREFIX)>=0){
				HashSet sAll = CacheHelper.getSessionAll();
				if(sAll.remove(keyStr)){								
				   CacheHelper.put(CacheKeyDefine.SESSION_ALL,sAll);
				}
			}
			else if(keyStr.indexOf(CacheKeyDefine.CHATGROUP_PREFIX)>=0){
				HashSet cAll = CacheHelper.getChatGroupAll();
				if(cAll.remove(keyStr)){
				   CacheHelper.put(CacheKeyDefine.CHATGROUP_ALL,cAll);
				}
			}
			else{								
			}
		}						
	}   	
}
